﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using BUS;

namespace QuanLyNhaSach.MainMenu
{
    public partial class FrmInvoiceBook : DevComponents.DotNetBar.Office2007Form
    {
        public ActionName Action { get; set; }
        CustomerDTO _customer;
        InvoiceBUS _invoiceBUS;

        public FrmInvoiceBook()
        {
            InitializeComponent();
            _customer = new CustomerDTO();
            _invoiceBUS = new InvoiceBUS();
            cmbBook.DisplayMember = BookColumn.BookName.ToString();
            cmbBook.ValueMember = BookColumn.BookID.ToString();
            colUnitPrice.DefaultCellStyle.Format = Global.CurrencyFormat;
            dtgInvoice.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dtgInvoice_EditingControlShowing);
        }

        void dtgInvoice_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            ComboBox cmbBox;
            if (dtgInvoice.CurrentCell.ColumnIndex == cmbBook.Index)
            {
                cmbBox = e.Control as ComboBox;
                if (cmbBox != null)
                {
                    //cmbBox.SelectedValueChanged += new EventHandler(cmbBox_SelectedValueChanged);
                    cmbBox.SelectedIndexChanged += new EventHandler(cmbBox_SelectedIndexChanged);
                    cmbBox.DropDownStyle = ComboBoxStyle.DropDown;
                    cmbBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                    cmbBox.AutoCompleteSource = AutoCompleteSource.ListItems;
                }
            }
        }

        void cmbBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {

                SetMessage(string.Empty, true);
                ComboBox cmbBox = (ComboBox)sender;
                cmbBox.SelectedIndexChanged -= cmbBox_SelectedIndexChanged;
                if (Global.intParse(cmbBox.SelectedValue) > 0)
                {
                    int bookID = int.Parse(cmbBox.SelectedValue.ToString());

                    BookBUS bookBUS = new BookBUS();
                    BookDTO bookDto = bookBUS.GetBookByID(bookID);
                    ParameterBUS parameterBUS = new ParameterBUS();
                    if (bookDto != null)
                    {
                        dtgInvoice.CurrentRow.Cells[colBookID.Index].Value = bookDto.BookID;
                        dtgInvoice.CurrentRow.Cells[colUnitPrice.Index].Value = bookDto.BookCost;
                        dtgInvoice.CurrentRow.Cells[colAuthor.Index].Value = bookDto.AuthorName;
                        dtgInvoice.CurrentRow.Cells[colCategory.Index].Value = bookDto.CategoryName;
                        dtgInvoice.CurrentRow.Cells[colStockQuantity.Index].Value = bookDto.StockQuantity;
                        dtgInvoice.CurrentRow.Cells[colQuantity.Index].Value = 1;
                        ComputeGrandTotal();
                    }

                    int lastRow = dtgInvoice.Rows.GetLastRow(DataGridViewElementStates.None);
                    if (lastRow > dtgInvoice.CurrentRow.Index &&
                        dtgInvoice[colBookID.Index, lastRow].Value != null)
                    {
                        dtgInvoice.Rows.Add(1);
                    }
                    else if (lastRow == dtgInvoice.CurrentRow.Index)
                    {
                        dtgInvoice.Rows.Add(1);
                    }
                }
                else
                {
                    ClearValueGrid(dtgInvoice.CurrentRow.Index);
                }
                cmbBox.SelectedIndexChanged += cmbBox_SelectedIndexChanged;
            }
            catch (FormatException ex)
            {
                Global.SetMessage(lblMessage, ex.Message, false);
            }
        }

        private void ComputeGrandTotal()
        {
            float grandTotal = 0;
            foreach (DataGridViewRow row in dtgInvoice.Rows)
            {
                if (row.Cells[colBookID.Index].Value != null)
                {
                    float price = float.Parse(row.Cells[colUnitPrice.Index].Value.ToString());
                    int quantity = int.Parse(row.Cells[colQuantity.Index].Value.ToString());
                    grandTotal += price * quantity;
                }
            }

            txtGrandTotal.Text = grandTotal.ToString(Global.CurrencyFormat);
        }

        private void ClearValueGrid(int index)
        {
            SetMessage(string.Empty, true);
            dtgInvoice[colBookID.Index, index].Value = null;
            dtgInvoice[colUnitPrice.Index, index].Value = null;
            dtgInvoice[colAuthor.Index, index].Value = null;
            dtgInvoice[colCategory.Index, index].Value = null;
            dtgInvoice[colStockQuantity.Index, index].Value = null;
            dtgInvoice[colQuantity.Index, index].Value = null;
        }

        private void chkMember_CheckedChanged(object sender, EventArgs e)
        {
            if (chkMember.Checked)
            {
                txtCustomerCode.Enabled = true;
            }
            else
            {
                txtCustomerCode.Enabled = false;
            }

            SetMessage(string.Empty, true);
        }

        private void SetMessage(string mess, bool isSuccess)
        {
            Global.SetMessage(lblMessage, mess, isSuccess);
        }

        private void btnAddNew_Click(object sender, EventArgs e)
        {
            LoadDocSequenceAndCombobox();
        }

        private void LoadDocSequenceAndCombobox()
        {
            SetMessage(string.Empty, true);
            DocSequenceBUS docSeqBUS = new DocSequenceBUS();
            txtInvoiceCode.Text = docSeqBUS.GetNextDocSequenceNumber(DocSequence.Invoice.ToString());
            dtpInvoiceDate.Value = DateTime.Now;
            txtCustomerCode.Clear();
            chkMember.Checked = true;
            txtDescription.Clear();

            BookBUS bookBUS = new BookBUS();
            cmbBook.DataSource = bookBUS.GetNewBindingList();

            dtgInvoice.Rows.Clear();
            txtGrandTotal.Clear();
            dtgInvoice.Rows.Add(1);
            ProcessButton();
        }

        private void ProcessButton()
        {
            if (Action == ActionName.Insert)
            {
                btnAdd.Visible = true;
                btnUpdate.Visible = false;
                btnDelete.Enabled = false;
                btnAdd.Enabled = true;
            }
            else
            {
                btnAdd.Visible = false;
                btnUpdate.Visible = true;
                btnDelete.Enabled = true;
            }
            dtgInvoice.ReadOnly = false;
        }

        private void dtgInvoice_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == colQuantity.Index)
            {
                int quantity = Global.intParse(dtgInvoice[e.ColumnIndex, e.RowIndex].Value);
                int stockQuantity = Global.intParse(dtgInvoice[colStockQuantity.Index,e.RowIndex].Value);
                if (quantity < 0)
                {
                    SetMessage("Số lượng phải lớn hơn 0.", false);
                    dtgInvoice[e.ColumnIndex, e.RowIndex].Value = 1;
                }
                else if(quantity > stockQuantity)
                {
                    SetMessage("Số lượng bán phải nhỏ hơn số lượng tồn.",false);
                    dtgInvoice[e.ColumnIndex,e.RowIndex].Value = 1;
                }

                ComputeGrandTotal();
            }
        }

        private void dtgInvoice_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            dtgInvoice[colDel.Index, e.RowIndex].Value = Properties.Resources.deletered;
            Global.GenerateNumber(dtgInvoice, colNumber.Index);
        }

        private void dtgInvoice_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = true;
        }

        private void dtgInvoice_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                if (e.ColumnIndex == colDel.Index && dtgInvoice[colBookID.Index, e.RowIndex].Value != null)
                {
                    if (Global.ShowMessageBoxDelete("Bạn muốn xóa dòng này ?") == DialogResult.Yes)
                    {
                        dtgInvoice.Rows.RemoveAt(e.RowIndex);
                        Global.GenerateNumber(dtgInvoice, colNumber.Index);
                        ComputeGrandTotal();
                    }

                    if (dtgInvoice.Rows.Count == 0)
                    {
                        dtgInvoice.Rows.Add(1);
                    }
                }
            }
        }

        private void FrmInvoiceBook_Load(object sender, EventArgs e)
        {
            LoadDocSequenceAndCombobox();
        }

        private void txtCustomerCode_Leave(object sender, EventArgs e)
        {
            
        }

        private void btnEditCustomerCode_Click(object sender, EventArgs e)
        {
            if (chkMember.Checked)
            {
                if (!Global.ValidateCustomerCode(txtCustomerCode.Text))
                {
                    SetMessage("Mã khách hàng không đúng!.", false);
                    txtCustomerName.Clear();
                    _customer = new CustomerDTO();
                }
                else
                {
                    SetMessage(string.Empty, true);
                    CustomerBUS customerBUS = new CustomerBUS();
                    _customer = customerBUS.GetCustomerByCode(txtCustomerCode.Text);
                    if (_customer != null)
                    {
                        if (customerBUS.CheckCustomerDebt(_customer))
                        {
                            txtCustomerName.Text = _customer.CustomerName;
                        }
                        else
                        {
                            SetMessage("Khách hàng nợ quá số nợ quy định,vui lòng thanh toán trước.", false);
                            txtCustomerName.Clear();
                            return;
                        }
                    }
                    else
                    {
                        txtCustomerName.Clear();
                        SetMessage("Mã khách hàng không tồn tại!.", false);
                    }
                }
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (_customer == null || _customer.CustomerID <= 0)
            {
                SetMessage("Chưa nhập mã khách hàng.", false);
                return;
            }

            if (!CheckStockQuantityAfterSell())
            {
                SetMessage("Có dòng có số lượng tồn sau khi bán nhỏ hơn quy định ( dòng màu đỏ ).", false);
                return;
            }

            //Map invoiceList and insert
            InvoiceDTO invoice = new InvoiceDTO();
            invoice.CreatedBy = Global.UserID;
            invoice.CreatedDate = dtpInvoiceDate.Value;
            invoice.CustomerID = _customer.CustomerID;
            invoice.Description = txtDescription.Text;
            invoice.GrandTotal = Global.floatParse(txtGrandTotal.Text);
            invoice.InvoiceCode = txtInvoiceCode.Text;
            invoice.ListInvoiceDetail = new List<InvoiceDetailDTO>();
            invoice.Status = true;

            foreach (DataGridViewRow row in dtgInvoice.Rows)
            {
                if (row.Cells[colBookID.Index].Value != null)
                {
                    InvoiceDetailDTO invoiceDetail = new InvoiceDetailDTO();
                    invoiceDetail.BookID = Global.intParse(row.Cells[colBookID.Index].Value);
                    invoiceDetail.Quantity = Global.intParse(row.Cells[colQuantity.Index].Value);
                    invoiceDetail.Status = true;
                    invoiceDetail.UnitPrice = Global.floatParse(row.Cells[colUnitPrice.Index].Value);

                    invoice.ListInvoiceDetail.Add(invoiceDetail);
                }
            }

            if (invoice.ListInvoiceDetail.Count <= 0)
            {
                SetMessage("Hóa đơn phải có ít nhất 1 dòng.", false);
                return;
            }

            if (_invoiceBUS.InsertInvoiceList(invoice))
            {
                SetMessage("Lập hóa đơn thành công.", true);
                dtgInvoice.Enabled = false;
                btnAdd.Enabled = false;
            }
            else
            {
                SetMessage("Có lỗi trong quá trình làm việc, vui lòng thử lại.", false);
            }
        }

        private bool CheckStockQuantityAfterSell()
        {
            try
            {
                bool success = true;
                foreach (DataGridViewRow row in dtgInvoice.Rows)
                {
                    if (row.Cells[colBookID.Index].Value != null)
                    {
                        int quantity = Global.intParse(row.Cells[colQuantity.Index].Value);
                        int stockQuantity = Global.intParse(row.Cells[colStockQuantity.Index].Value);
                        if (!_invoiceBUS.CheckQuantityStockAfterSell(stockQuantity - quantity))
                        {
                            success = false;
                            row.DefaultCellStyle.ForeColor = Color.Red;
                        }
                        else
                        {
                            row.DefaultCellStyle.ForeColor = Color.Black;
                        }
                    }
                }

                return success;
            }
            catch (Exception ex)
            {
                SetMessage(ex.Message, false);
                return false;
            }
        }
    }
}
